package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传管理
 */
@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class UploadController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) throws IOException {
        log.info(file.getName());

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 构建新的文件名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 将文件保存在 D:/files/ 路径下
        String fileName = UUID.randomUUID().toString() + extension;

        // 本地上传文件
        file.transferTo(new File("D:/files/" + fileName));
        return Result.success();

//        try {
//            String filePath = aliOssUtil.upload(file.getBytes(), fileName);
//            return Result.success();
//        } catch (IOException ex) {
//            log.error("文件上传失败：{}", ex.getMessage());
//        }
//        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
